/*
 *MIT License
 *
 *Copyright (c) 2019 chenshuai cs4380@163.com
 *
 *Permission is hereby granted, free of charge, to any person obtaining a copy
 *of this software and associated documentation files (the "Software"), to deal
 *in the Software without restriction, including without limitation the rights
 *to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *copies of the Software, and to permit persons to whom the Software is
 *furnished to do so, subject to the following conditions:
 *
 *The above copyright notice and this permission notice shall be included in all
 *copies or substantial portions of the Software.
 *
 *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 *SOFTWARE.
 */

package com.cs.cslc.auth.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

/**
 * VerifyCodeUtils 验证码生成器.
 *
 * @author cs4380 https://gitee.com/xhbug_cs4380  cs4380@163.com
 * @version 1.0
 * @since 2021-12-14
 */
public class VerifyCodeUtils {
    /**
     * 生成验证码图片的宽度
     */
    private static final int WIDTH = 100;
    /**
     * 生成验证码图片的高度
     */
    private static final int HEIGHT = 30;
    /**
     * 字体
     */
    private static final String[] FONT_NAMES = {"宋体", "楷体", "微软雅黑"};
    /**
     * 定义验证码图片的背景颜色为白色
     */
    private static final Color bgColor = new Color(255, 255, 255);
    /**
     * 从下面的字符串中挑选字符放入验证码集中，去掉1、l、L等容易混淆的字符
     */
    private static final String CODES = "023456789abcdefghijkmnopqrstuvwxyzABCDEFGHIJKMNOPQRSTUVWXYZ";
    /**
     * 随机数对象
     */
    private static final Random random = new Random();

    /**
     * 生成的验证码
     */
    private String verifyCode;

    /**
     * 验证码位数
     */
    private static final int VERIFY_CODE_NUMBER = 4;

    /**
     * 获取一个随意颜色
     *
     * @return 颜色对象
     */
    private Color randomColor() {
        int red = random.nextInt(150);
        int green = random.nextInt(150);
        int blue = random.nextInt(150);
        return new Color(red, green, blue);
    }

    /**
     * 获取一个随机字体
     *
     * @return 获取一个字体
     */
    private Font randomFont() {
        String name = FONT_NAMES[random.nextInt(FONT_NAMES.length)];
        int style = random.nextInt(4);
        int size = random.nextInt(5) + 24;
        return new Font(name, style, size);
    }

    /**
     * 获取一个随机字符
     *
     * @return 随机码
     */
    private char randomChar() {
        return CODES.charAt(random.nextInt(CODES.length()));
    }

    /**
     * 创建一个空白的BufferedImage对象
     *
     * @return BufferedImage对象
     */
    private BufferedImage createImage() {
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = (Graphics2D) image.getGraphics();
        // 设置验证码图片的背景颜色
        g2.setColor(bgColor);
        g2.fillRect(0, 0, WIDTH, HEIGHT);
        return image;
    }

    /**
     * 生成验证码图片对象
     *
     * @return 验证码图片对象
     */
    public BufferedImage getImage() {
        BufferedImage image = createImage();
        Graphics2D g2 = (Graphics2D) image.getGraphics();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < VERIFY_CODE_NUMBER; i++) {
            String s = randomChar() + "";
            sb.append(s);
            g2.setColor(randomColor());
            g2.setFont(randomFont());
            float x = i * WIDTH * 1.0f / 4;
            g2.drawString(s, x, (float) HEIGHT - 8);
        }
        this.verifyCode = sb.toString();
        drawLine(image);
        return image;
    }

    /**
     * 验证码图片中添加干扰线
     *
     * @param image 验证码图片对象
     */
    private void drawLine(BufferedImage image) {
        Graphics2D g2 = (Graphics2D) image.getGraphics();
        int num = 7;
        for (int i = 0; i < num; i++) {
            int x1 = random.nextInt(WIDTH);
            int y1 = random.nextInt(HEIGHT);
            int x2 = random.nextInt(WIDTH);
            int y2 = random.nextInt(HEIGHT);
            g2.setColor(randomColor());
            g2.setStroke(new BasicStroke(1.5f));
            g2.drawLine(x1, y1, x2, y2);
        }
    }

    /**
     * 获取生成的验证码
     *
     * @return 生成的验证码
     */
    public String getVerifyCode() {
        return verifyCode;
    }

    /**
     * 输出验证码图片
     *
     * @param image 验证码图片
     * @param out   输出对象
     * @throws IOException 异常
     */
    public static void output(BufferedImage image, OutputStream out) throws IOException {
        ImageIO.write(image, "JPEG", out);
    }
}

